﻿using System;
using System.Collections.Generic;
using System.Linq;
using Toon.Models.Catalogs;

namespace Toon.Models.Characters
{
	public class StandardRules : RuleSet
	{
		/// <summary>
		/// Initializes a new instance of the StandardRules class.
		/// </summary>
		/// <param name="catalog"></param>
		public StandardRules(Catalog catalog)
			: base(catalog)
		{

		}
		
		public override Character CreateNewCharacter()
		{
			var result = new Character(this);
			foreach (var a in result.Attributes)
				a.Value = result.Random.D6();
			result.HitPoints = 6 + result.Random.D6();

			result.AcceptChanges();

			return result;
		}

		public override Character CreateRandomCharacter()
		{
			var result = CreateNewCharacter();
			var rand = result.Random;

			result.Species = Catalog.Species.ChooseOne(rand);

			var x1 = rand.D6() + rand.D6();
			if (x1 < 3)
				result.NaturalEnemies = "None";
			if (x1 > 3)
				result.NaturalEnemies = Catalog.NaturalEnemies.ChooseOne(rand);
			if (x1 >= 11)
				result.NaturalEnemies += ", " + Catalog.NaturalEnemies.ChooseOne(rand);



			result.Occupation = Catalog.Occupation.ChooseOne(rand);

			var allSkills = new List<Skill>();
			foreach (var a in result.Attributes)
				allSkills.AddRange(a.Skills);

			//Add 0, 1, or 2 shitcks
			var allShitcks = Catalog.Shitcks.ToList();
			var x2 = rand.D6() + rand.D6();
			if (x2 > 3)
				result.Shitcks.Add(new Shitck(rand.ChooseAndRemove(allShitcks)));
			if (x2 >= 11)
				result.Shitcks.Add(new Shitck(rand.ChooseAndRemove(allShitcks)));

			//Randomly assign remaining skill points. 
			while (result.UnspentSkillPoints > 0)
			{
				var skill = rand.ChooseOne(allSkills);
				var adds = rand.D3();
				if (adds > result.UnspentSkillPoints)
					adds = result.UnspentSkillPoints;
				if (adds + skill.SkillLevel > 9)
					adds = 9 - skill.SkillLevel;

				skill.SkillPoints += adds;

				if (skill.SkillLevel >= 9)
					allSkills.Remove(skill);
			}


			AddRandomPossessions(result);

			result.AcceptChanges();

			return result;
		}

	}
}

